import  sqlite3
import threading

# 创建线程本地存储对象
thread_local = threading.local()
class SqliteDb():

    def __init__(self, db):
        self.db_path = db
        # 不再在此处创建连接，改为在get_connection中创建
    
    def get_connection(self):
        """为当前线程获取或创建数据库连接"""
        if not hasattr(thread_local, "conn"):
            # 为当前线程创建连接和游标
            thread_local.conn = sqlite3.connect(self.db_path)
            thread_local.cur = thread_local.conn.cursor()
        return thread_local.conn, thread_local.cur
    
    def close_connection(self):
        """关闭当前线程的数据库连接"""
        if hasattr(thread_local, "cur"):
            thread_local.cur.close()
        if hasattr(thread_local, "conn"):
            thread_local.conn.close()
        # 清除线程本地存储中的连接对象
        if hasattr(thread_local, "conn"):
            del thread_local.conn
        if hasattr(thread_local, "cur"):
            del thread_local.cur
    def __enter__(self):
        """进入上下文时获取连接"""
        return self.get_connection()

    def __exit__(self, exc_type, exc_val, exc_tb):
        """退出上下文时关闭连接"""
        self.close_connection()

    def select_db(self, sql):
        """查询"""
        conn, cur = self.get_connection()
        try:
            cur.execute(sql)
            data = cur.fetchall()
            return data
        except Exception as e:
            print(f"查询出现错误：{e}")
            return None
    
    def execute_db(self, sql):
        """更新/插入/删除"""
        conn, cur = self.get_connection()
        try:
            cur.execute(sql)
            conn.commit()
            return cur.rowcount
        except Exception as e:
            print(f"操作出现错误：{e}")
            conn.rollback()
            return 0
    
    def executemany_db(self, sql, data_list):
        """批量操作"""
        conn, cur = self.get_connection()
        try:
            cur.executemany(sql, data_list)
            conn.commit()
            return cur.rowcount
        except Exception as e:
            print(f"批量操作出现错误：{e}")
            conn.rollback()
            return 0
    # 在 SqliteDb 类中添加以下方法
    
